from flask import Blueprint, request
from flask_jwt_extended import jwt_required, get_jwt_identity

from service.category_service import add_category, get_category, update_category, delete_category
from utils import response

category_bp = Blueprint("category", __name__, url_prefix="/category")
from log import logger

@category_bp.route("/addCategory", methods=['POST'])
@jwt_required()
def add_category_router():
    body = request.get_json()
    try:
        category_name = body["category_name"]
        category_alias = body["category_alias"]
    except Exception as ex:
        return response(400, f"缺少参数{ex}", None)

    sub = get_jwt_identity()

    try:
        add_category(user_id=sub['user_id'],
                     username=sub['username'],
                     category_name=category_name,
                     category_alias=category_alias)

        return response(200, "文章分类创建成功", None)
    except Exception as ex:
        return response(500, str(ex), None)


@category_bp.route("/getCategory", methods=['GET'])
def get_category_router():
    try:
        data = get_category()

        return response(200, "查询文章分类成功", data)
    except Exception as ex:
        return response(500, str(ex), None)


@category_bp.route("/updateCategory", methods=['PUT'])
def update_category_router():
    body = request.get_json()
    try:
        category_id = body["category_id"]
    except Exception as ex:
        return response(400, f"缺少参数{ex}", None)

    category_name = body.get("category_name")
    category_alias = body.get("category_alias")

    try:
        update_category(category_id=category_id,
                        category_name=category_name,
                        category_alias=category_alias)

        return response(200, "文章类别更新成功", None)
    except Exception as ex:
        return response(500, str(ex), None)


@category_bp.route("/deleteCategory", methods=['DELETE'])
def delete_category_router():
    body = request.get_json()
    try:
        category_id = body["category_id"]
    except Exception as ex:
        return response(400, f"缺少参数{ex}", None)

    try:
        delete_category(category_id=category_id)

        return response(200, "文章类别删除成功", None)
    except Exception as ex:
        return response(500, str(ex), None)
